<?php
include_once($_SERVER['DOCUMENT_ROOT']."/common/config.php");
$_conn = connect_mysql('bangumi');

include_once("bilibili.php");

if(!preg_match('/^\d{1}$/', $_GET['weekday']) || !preg_match('/^[23]$/', $_GET['ch'])){
	$error = "信息不全";
}else{
	$weekday = $_GET['weekday'];
	$ch = $_GET['ch'];
	$sql = "SELECT title, cover, spid, click, weekday, new, area, UNIX_TIMESTAMP(lastupdate) AS lastupdate, UNIX_TIMESTAMP(time) AS time FROM bangumi_list WHERE ch = '$ch' AND weekday = '$weekday' ORDER BY lastupdate DESC";
	$result = mysqli_query($_conn, $sql) or die("数据库错误");
	while($row = mysqli_fetch_assoc($result)){
		if(time() - $row['time'] > 2 * 60 * 60){
			unset($bangumi_list);
			$sql = "TRUNCATE TABLE bangumi_list";
			mysqli_query($_conn, $sql) or die(mysqli_error($_conn));
			break;
		}
		$bangumi_list[] = array(
			'title' => urlencode($row['title']),
			'cover' => $row['cover'],
			'spid' => $row['spid'],
			'click' => $row['click'],
			'lastupdate' => $row['lastupdate'],
			'new' => $row['new'],
			'area' => urlencode($row['area']),
			'weekday' => $row['weekday']
		);
	}
		
	if(!isset($bangumi_list)){
		$params = array(
			'btype' => $ch
		);	
		$result = get_bilibili('bangumi', $params);
		$list = json_decode($result);
		if($list && $list->code == '0'){
			foreach($list->list as $row){
				$bangumi_list[] = array(
					'title' => urlencode($row->title),
					'cover' => $row->cover,
					'spid' => $row->spid,
					'click' => $row->click,
					'lastupdate' => $row->lastupdate,
					'new' => $row->new,
					'area' => urlencode($row->area),
					'weekday' => $row->weekday
				);
				$sql = "INSERT INTO bangumi_list (ch, weekday, title, cover, spid, click, area, new, lastupdate, time) SELECT '{$ch}', '{$row->weekday}', '{$row->title}', '{$row->cover}', '{$row->spid}', '{$row->click}', '{$row->area}', '{$row->new}', FROM_UNIXTIME('{$row->lastupdate}'), NOW() FROM dual WHERE NOT EXISTS (SELECT * FROM bangumi_list WHERE bangumi_list.title = '{$row->title}');";
				mysqli_query($_conn, $sql) or die(mysqli_error($_conn));	
			}
		}else{
			$error = "获取数据失败";
		}
	}
}

if(!isset($error) || isset($bangumi_list)){
	$error = null;
}else{
	$error = "数据错误";
}

$data = array(
	'error' => urlencode($error),
	'list' => $bangumi_list
);
echo urldecode(stripslashes(json_encode($data)));